package com.redhat.redwork.ognl;

import static junit.framework.Assert.assertEquals;

import java.util.HashMap;
import java.util.Map;

import ognl.Ognl;

import org.junit.Test;

class User {
	private Integer id;
	private String name;
	private Department department = new Department();
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Department getDepartment() {
		return department;
	}
	public void setDepartment(Department department) {
		this.department = department;
	}
}

class Department {
	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

public class OGNLTestCase {

	static final String USERNAME = "Justin";
	static final String INTRO_STR = "My name is ";
	
	@SuppressWarnings("unchecked")
	@Test
	public void test_get_value() throws Exception{
		// Create root object  
        User user = new User();  
        user.setId(1);  
        user.setName(USERNAME);  
  
        // Create context  
        Map context = new HashMap();
        context.put("introduction",INTRO_STR);
          
		// Test to directly get value from root object, with no context
		Object name = Ognl.getValue(Ognl.parseExpression("name"), user);
		assertEquals(USERNAME, name);
		name = Ognl.getValue("name", user);
		assertEquals(USERNAME, name);
          
        // Test to get value(parameter) from context  
        Object contextValue = Ognl.getValue(Ognl.parseExpression("#introduction"), context, user);  
        assertEquals(INTRO_STR, contextValue);  
        
     // Test to get value(parameter) from context  
        contextValue = Ognl.getValue("#introduction", context, user);
        assertEquals(INTRO_STR, contextValue);
          
        // Test to get value and parameter from root object and context  
        Object hello = Ognl.getValue(Ognl.parseExpression("#introduction + name"), context, user);  
		assertEquals(INTRO_STR + USERNAME, hello);
	}
	
	public void test_set_value() throws Exception{
		// Create root object  
        User user = new User();  
        user.setId(1);  
        user.setName(USERNAME);
          
                // Set value according to the expression  
        Ognl.setValue("department.name", user, "dev");  
        assertEquals("dev", user.getDepartment().getName());  
	}
}
